﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YY.Admin.Core.Models;

namespace YY.Admin.Core.SqlSugar
{
    public class SqlSugarDbContext : ISqlSugarDbContext
    {
        public SqlSugarScope Db { get; }

        public SqlSugarDbContext()
        {
            Db = new SqlSugarScope(new ConnectionConfig()
            {
                ConnectionString = "Data Source=./Admin.NET.db;",
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });

            Db.Aop.OnLogExecuting = (sql, pars) =>
            {
                var log = $"【{DateTime.Now}——执行SQL】\r\n{UtilMethods.GetNativeSql(sql, pars)}\r\n";
                var originColor = Console.ForegroundColor;
                if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
                    Console.ForegroundColor = ConsoleColor.Green;
                if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
                    Console.ForegroundColor = ConsoleColor.Yellow;
                if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
                    Console.ForegroundColor = ConsoleColor.Red;
                Debug.WriteLine(log);
                Console.ForegroundColor = originColor;
            };
        }

        public void InitializeDatabase()
        {
            Db.CodeFirst.InitTables(typeof(User));
        }
    }
}
